//= require jquery.dataTables.min.js
var stock_table;

$(document).ready(function(){
  $(".stock").click(function(){add_sold($(this));});
  $("#sold_stocks").hide()
  $("#solds").on("change","input",function(){
    update_bill_total();
  });
  stock_table = $('#stocks').dataTable({
    "bPaginate": false,
    "bLengthChange": false,
    "bFilter": true,
    "bSort": true,
    "bInfo": false,
    "bAutoWidth": false
  });
});

function add_sold(row) {
  var new_id = new Date().getTime();
  var regexp = new RegExp("new_sold", "g");
  $("#solds tbody").append(content.replace(regexp, new_id));
  var added_row = $("#solds tr:last");
  added_row.find(".name").text(row.find(".name").text());
  added_row.find(".company").text(row.find(".company").text());
  added_row.find(".sale_cost input").val(row.find(".sale_cost").text());
  added_row.find(".quantity input").val("1");
  added_row.find(".tax_percentage input").val(row.find(".tax_percentage").text());
  added_row.find(".commission_percentage input").val(row.attr("commission_percentage"));
  added_row.find(".stock_id").val(row.attr("id"));
  hide_sold_stock(row);
  update_bill_total();
}

function hide_sold_stock(row){
  stock_table.fnDeleteRow(stock_table.fnGetPosition(row.find('td')[0])[0]);
  $("#sold_stocks").append(row)
}

function update_bill_total(){
  var grandTotal = 0;
  $("tr.sold").each(function(){
    var row = $(this);
    var quantity = row.find(".quantity input").val();
    var cost = row.find(".sale_cost input").val();
    var total_cost = cost * quantity;
    var tax = total_cost * row.find(".tax_percentage input").val()/100;
    var commission = total_cost * row.find(".commission_percentage input").val()/100;
    var total_sale_cost = (parseFloat(total_cost)+parseFloat(tax)+parseFloat(commission)).toFixed(2);
    row.find('.total').text(total_sale_cost);
    grandTotal = parseFloat(row.find('.total').text()) + parseFloat(grandTotal);
  });
  $(".grand_total").val(grandTotal.toFixed(2));
}

